const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const crypto = require('crypto');
const algorithm = 'aes-192-cbc';
const iv = Buffer.alloc(16, 1);  // 加密算法向量，16位，全1

function getRandomStr(length) {
  let x="0123456789qwertyuioplkjhgfdsazxcvbnm";
  let randomStr="";
  for(let i=0; i<length; i++)  {
    randomStr += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
  }
  return randomStr;
}

module.exports = (db, DataTypes) => {
  return db.define('User', {
    username: {
      type: DataTypes.STRING,
      unique: true,
    },
    teamName: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    isTeamLeader: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
    },
    avatar: {
      type: DataTypes.STRING,
      defaultValue: '/avatar.png',
    },
    password: {
      type: DataTypes.TEXT,
      allowNull: false,
      set(password) {
        let salt = getRandomStr(32);  // 获取随机盐值
        const key = crypto.scryptSync(password, salt, 24); // 密码加盐生成hash buffer
        const encrypted = crypto.createCipheriv(algorithm, key, iv).final('hex'); // 再使用加密算法加密
        this.setDataValue('password', encrypted);
        this.setDataValue('salt', salt);  // 存储盐值
      }
    },
    salt: DataTypes.STRING, // 将salt当作用户的Session，为了简便起见，这个Session不会过期
    phone: DataTypes.STRING,
    email: DataTypes.STRING,
    createdAt: DataTypes.DATE,
    updatedAt: DataTypes.DATE,

    description: {  // 对用户的描述
      type: DataTypes.TEXT,
    },
    isStop: {   // 用户是否被停用，登录时判断
      type: DataTypes.BOOLEAN,
      defaultValue: false,
    },

    active: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
    }
  }, {
    defaultScope: {
      where: {
        active: true,
      }
    },
    scopes: {
      all: {
        where: {
          [Op.or]: [{
            active: true,
          },{
            active: false,
          }]
        }
      }
    },
    associate(models) {
      // models.User.belongsTo(models.BrowsePrivileges, { as: 'BrowsePrivileges', foreignKey: 'BrowsePrivilegeId' });
      models.User.hasMany(models.ApprovalPrivileges, { as: 'ApprovalPrivileges' });
      models.User.hasMany(models.Message);
      models.User.belongsToMany(models.RequestNote, {  // 申请与审批记录表
        through: {
          model: 'UserRequestNote',
          unique: false,
        },
        foreignKey: "UserId",
        constraints: false,
      });
      models.User.belongsTo(models.Department, { as: 'Department', foreignKey: 'DepartmentId' });
      // models.User.belongsTo(models.UserRequestNote, { foreignKey: 'RequestNoteId' }); // 这种写法错误！
    }
  });
};
